﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 面板管理员
/// 功能：面板的层级管理，提供打开和关闭面板的工具函数
/// </summary>
public class PanelMgr : MonoBehaviour
{
    // 单例
    public static PanelMgr Instance;
    // 画布
    private GameObject canvas;
    // 已打开的面板
    public Dictionary<string, PanelBase> dict;
    // 各个层级的位置
    private Dictionary<PanelLayer, Transform> layerDict;

    // 开始
    public void Awake()
    {
        Instance = this;
        InitLayer();
        dict = new Dictionary<string, PanelBase>();
    }

    // 初始化层
    private void InitLayer()
    {
        // 画布
        canvas = GameObject.Find("Canvas");
        if(canvas == null)
        {
            Debug.LogError("PanelMgr.InitLayer fail,canvas is null");
        }
        // 各个层级
        layerDict = new Dictionary<PanelLayer, Transform>();
        foreach (PanelLayer pl in Enum.GetValues(typeof(PanelLayer)))//Enum.GetValues返回枚举类型取值的遍历
        {
            string name = pl.ToString();
            Transform transform = canvas.transform.Find(name);
            layerDict.Add(pl,transform);
        }
    }

    // 分层类型
    public enum PanelLayer
    {
        // 面板
        Panel,
        // 提示
        Tips,
    }

    /// <summary>
    /// 打开面板
    /// </summary>
    /// <typeparam name="T">PanelBase的类型</typeparam>
    /// <param name="skinPath">面板皮肤路径动态获取</param>
    /// <param name="args">面板参数</param>
    public void OpenPanel<T>(string skinPath, params object[] args) where T : PanelBase
    {
        //已经打开的情况
        string name = typeof(T).ToString();
        if (dict.ContainsKey(name))
        {
            return;
        }
        //面板脚本
        PanelBase panel = canvas.AddComponent<T>();
        panel.Init(args);
        dict.Add(name, panel);
        //加载皮肤
        skinPath = (skinPath != "" ? skinPath : panel.skinPath);
        GameObject skin = Resources.Load<GameObject>(skinPath);//动态加载Resources下的皮肤
        if (skin == null)
        {
            Debug.LogError("panelMgr.OpenPanel fail, skin is null, skinPath = " + skinPath);
        }
        panel.skin = (GameObject)Instantiate(skin);
        //坐标
        Transform skinTrans = panel.skin.transform;
        PanelLayer layer = panel.layer;
        Transform parent = layerDict[layer];
        skinTrans.SetParent(parent, false);//设置parent为skin父级，即把skin添加到层级当中去
        //生命周期
        panel.OnShowing();
        //anm
        panel.OnShowed();
    }

    /// <summary>
    /// 关闭面板
    /// </summary>
    /// <param name="name">关闭的面板名称</param>
    public void ClosePanel(string name)
    {
        PanelBase panel = (PanelBase)dict[name];
        if (panel == null)
        {
            return;
        }

        panel.OnClosing();
        dict.Remove(name);
        panel.OnClosed();
        GameObject.Destroy(panel.skin);
        Component.Destroy(panel);
    }
}
